package cn.hengzhu.main_manager.utils;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.hengzhu.main_manager.utils.config.AliMessageConfig;

public class MessageUtil {

	/**
	 * @author liuCheng
	 * @since 2018年11月30日 上午9:57:44
	 * @return 生成随机四位数
	 */
	public static String getCode() {
		Integer key = (int) ((Math.random() * 9 + 1) * 1000);
		return key.toString();
	}

	/**
	 * @author liuCheng
	 * @since 2018年11月30日 下午1:49:44
	 * @param phoneNumber
	 * @param signName
	 * @param templateCode
	 * @return
	 * @throws ServerException 
	 * @throws ClientException
	 *             存放快递的短信发送
	 */
	public static Boolean sendSms(String phoneNumber, String address,String code) throws Exception {

		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliMessageConfig.ACCESSKEY_ID,
				AliMessageConfig.ACCESS_KEY_SECRET);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", AliMessageConfig.PRODUCT, AliMessageConfig.DOMAIN);
		IAcsClient acsClient = new DefaultAcsClient(profile);

		SendSmsRequest request = new SendSmsRequest();

		request.setPhoneNumbers(phoneNumber);
		request.setSignName(AliMessageConfig.SIGN_NAME);
		request.setTemplateCode(AliMessageConfig.TEMPLATE_CODE);
		
		Map<String, String> map = new HashMap<>();
		map.put("address", address);
		map.put("code", code);
		String jsonString = JSONObject.toJSONString(map);
		request.setTemplateParam(jsonString);

		// hint 此处可能会抛出异常，注意catch
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		String returnCode = sendSmsResponse.getCode();
		if(returnCode.equals("OK")){
			return true;
		}else{
			return false;
		}
	}

}





